package com.xp.basic.heima.nio.netty.simpledemo.chat.server;

import com.xp.basic.heima.nio.netty.simpledemo.chat.handler.ChatRequestHandler;
import com.xp.basic.heima.nio.netty.simpledemo.chat.handler.LoginReuqestMessageHandler;
import com.xp.basic.heima.nio.netty.simpledemo.chat.handler.RpcRequestHandler;
import com.xp.basic.heima.nio.netty.simpledemo.chat.protocol.MessageCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

public class ChatServerTest {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup(2);
        //HANDLE
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodec MESSAGE_CODEC = new MessageCodec();
        LoginReuqestMessageHandler LOGGIN_REQUEST_HANDLER = new LoginReuqestMessageHandler();
        ChatRequestHandler CHAT_REQUEST_HANDLER = new ChatRequestHandler();
        RpcRequestHandler RPC_HANDLER = new RpcRequestHandler();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss,worker);
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,12,4,0,0));
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(LOGGIN_REQUEST_HANDLER);
                    ch.pipeline().addLast(CHAT_REQUEST_HANDLER);
                    ch.pipeline().addLast(RPC_HANDLER);
                }
            });

            Channel channel = serverBootstrap.bind(new InetSocketAddress(8080)).sync().channel();
            channel.closeFuture().sync();

        }catch (Exception e){
            System.out.println(" error : "+ e.getMessage());
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

}
